package com.zbkj.common.utils.file;


import com.tiangong.framework.bo.CDO;
import com.zbkj.common.utils.IpUtil;
import com.zbkj.common.utils.oss.OSSUtil;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.util.CellRangeAddress;


import javax.swing.*;
import java.io.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class FileExportImportUtil {

    InputStream os;
    List<List<String>> list = new ArrayList<List<String>>();

    //创建工作本
    public HSSFWorkbook demoWorkBook = new HSSFWorkbook();
    //创建表
    public HSSFSheet demoSheet = demoWorkBook.createSheet("Sheet1");

    /**
     * 创建行
     *
     * @param cells
     * @param rowIndex
     */
    public void createTableRow(List<String> cells, int rowIndex) {
        //创建第rowIndex行
        Row row = demoSheet.createRow(rowIndex);
        for (int i = 0; i < cells.size(); i++) {
            //创建第i个单元格
            Cell cell = row.createCell(i);
            cell.setCellValue(cells.get(i));
        }
    }

    /**
     * 创建整个Excel表
     *
     * @throws SQLException
     */
    public void createExcelSheet() throws SQLException {
        for (int i = 0; i < list.size(); i++) {
            createTableRow((List<String>) list.get(i), i);
        }
    }

    /**
     * 导出表格
     *
     * @param sheet
     * @throws IOException
     */
    public InputStream exportExcel(HSSFSheet sheet) throws IOException {
        sheet.setGridsPrinted(true);
        HSSFFooter footer = sheet.getFooter();
        footer.setRight("Page " + HSSFFooter.page() + " of " +
                HSSFFooter.numPages());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            demoWorkBook.write(baos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] ba = baos.toByteArray();
        os = new ByteArrayInputStream(ba);
        return os;
    }


    public InputStream export(List<List<String>> zlist) {
        InputStream myos = null;
        try {
            list = zlist;
            createExcelSheet();
            myos = exportExcel(demoSheet);
            return myos;
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "表格导出出错，错误信息 ：" + e + "\n错误原因可能是表格已经打开。");
            e.printStackTrace();
            return null;
        } finally {
            try {
                os.close();
                if (myos != null) myos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    public HSSFWorkbook getHSSFWorkbook(List<List<String>> zlist) {
        try {
            list = zlist;
            createExcelSheet();
            //myos= exportExcel(demoSheet);
            demoSheet.setGridsPrinted(true);
            HSSFFooter footer = demoSheet.getFooter();
            footer.setRight("Page " + HSSFFooter.page() + " of " +
                    HSSFFooter.numPages());
            return demoWorkBook;
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "表格导出出错，错误信息 ：" + e + "\n错误原因可能是表格已经打开。");
            e.printStackTrace();
            return null;
        }

    }


    /**
     * 创建excel
     *
     * @param headName 表头
     * @param list     数据字符串集合
     * @param expName  文件名
     * @param dir      文件路径
     * @return
     * @throws Exception
     */
    public static File createExcel(String[] headName, List<List<String>> list, String expName, String dir) throws Exception {
        // 格式化时间
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("sheet1");
        // 创建表头
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0);
        for (int y = 0; y < headName.length; y++) {//循环表头信息
            cell = row.createCell(y);
            cell.setCellValue(headName[y]);
        }
        for (int x = 0; x < list.size(); x++) {//循环数据信息
            row = sheet.createRow(x + 1);
            List<String> rowString = list.get(x);
            for (int i = 0; i < rowString.size(); i++) {
                cell = row.createCell(i);
                cell.setCellValue(rowString.get(i));
            }
        }
        FileUtils.deleteFile(dir + "/" + expName + ".xlsx");
        new File(dir).mkdirs();
        String filePath = dir + "/" + expName + ".xlsx";
        File file = noExists(filePath);

        FileOutputStream fos = new FileOutputStream(file);
        workbook.write(fos);
        fos.close();
        return file;
    }

    public static File noExists(String filePath) {
        File file = new File(filePath);
        int i = 1;
        while (file.exists()) {
            file = new File(filePath.split("\\.")[0] + "（" + i + "）." + filePath.split("\\.")[1]);
            i++;
        }
        return file;
    }

//2.导出 （性别 生日 职业）（qq和微信 不要）（求职的地方，拿ip判断）

    public static String uploadSupportingOfficerFile(List<CDO> list, String time, String SecondedName) throws IOException {
        String[] titles = {"序列","职位" ,"姓名", "电话", "邮箱","性别","生日","职业","求职地点","是否录取","报名时间"};
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet hssfSheet = workbook.createSheet();
        HSSFRow row = hssfSheet.createRow(0);
        HSSFCellStyle hssfCellStyle = workbook.createCellStyle();
        HSSFCell hssfCell = null;
        for (int i = 0; i < titles.length; i++) {
            hssfCell = row.createCell(i);//列索引从0开始
            hssfCell.setCellValue(titles[i]);//列名
            hssfCell.setCellStyle(hssfCellStyle);//列居中显示
        }
        for (int i = 0; i < list.size(); i++) {
            row = hssfSheet.createRow(i + 1);
            //序号
            row.createCell(0).setCellValue(i + 1);
            //职位
            row.createCell(1).setCellValue(list.get(i).getString("title"));
            //姓名
            row.createCell(2).setCellValue(list.get(i).getString("userName"));
            //电话
            row.createCell(3).setCellValue(list.get(i).getString("userTel"));
            //邮箱
            row.createCell(4).setCellValue(list.get(i).getString("userEmail"));
            //性别
            row.createCell(5).setCellValue(list.get(i).getInteger("userSex")==1?"男":"女");
            //生日
            row.createCell(6).setCellValue(list.get(i).getString("userBirthday"));
            //职位
            row.createCell(7).setCellValue(list.get(i).getInteger("userCareer")==1?"自由人":list.get(i).getInteger("userCareer")==1?"上班组":"学生党");
            //详细位置
            row.createCell(8).setCellValue(list.get(i).getString("userLocation"));
            //状态
            row.createCell(9).setCellValue(list.get(i).getInteger("admissionState")==1?"录取":"未录取");

            //邮箱
            row.createCell(10).setCellValue(list.get(i).getString("applicationTime"));
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        System.out.println(baos);
        workbook.write(baos);
        byte[] ba = baos.toByteArray();
        InputStream os = new ByteArrayInputStream(ba);
        String expName =  time;
        String uploadExcelFile = OSSUtil.uploadExcelFile(os, expName);// kit! 为名称
        System.err.println(uploadExcelFile);
        os.close();
        return uploadExcelFile;
    }


}




